package mergeSortThread;

public class MergeSort implements Runnable {

	private int[] initial;
	private int[] sortedArray;

	public MergeSort(int[] initial) {
		this.initial = initial;
	}

	private int[] sort(int[] inputArray) {
		int[] sorted;
		if (inputArray.length != 1) {

			int mid = inputArray.length / 2;

			int[] left = new int[mid];
			int[] right = new int[inputArray.length - mid];
			System.arraycopy(inputArray, 0, left, 0, mid);
			MergeSort ms1 = new MergeSort(left);
			Thread t1 = new Thread(ms1);
			t1.start();

			System.arraycopy(inputArray, mid, right, 0, inputArray.length - mid);

			right = sort(right);
			try {
				t1.join();
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
			left = ms1.sortedArray;

			sorted = merge(left, right);
		} else {
			return inputArray;
		}

		return sorted;
	}

	private int[] merge(int[] left, int[] right) {

		int[] merged = new int[left.length + right.length];

		int i = 0, j = 0, k = 0;

		while (i < left.length && j < right.length) {
			if (left[i] >= right[j]) {
				merged[k] = left[i++];

			} else {
				merged[k] = right[j++];

			}
			k++;
		}
		if (j == right.length) {
			System.arraycopy(left, i, merged, k, merged.length - k);
			i += merged.length - k;
		} else if (i == left.length) {
			System.arraycopy(right, j, merged, k, merged.length - k);
			j += merged.length - k;
		}
		k += merged.length - k;

		return merged;

	}

	public int[] getSortedArray() {
		return sortedArray;
	}

	@Override
	public void run() {
		sortedArray = sort(initial);

	}

	public void sort() {
		run();
	}

}
